package com.example.outdoor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.xml.sax.Parser;

import android.R.integer;
import android.R.string;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings.System;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

public class mainVerification extends Activity implements OnClickListener,
		OnItemSelectedListener {
	private static final int CAMERA_REQUEST = 1888;
	private static String DBNAME = "OutdoorAppDB.db";
	public static ArrayList<String> arr;
	String ANTERIOR = "ANTERIOR";
	String AvenueCodeMain;
	Spinner CarrierSpn;
	Spinner CategorySpnNew;
	Button DeleteButton;
	String FirstCategory = "";
	String FirstNewProduct = "";
	String FirstNewVersion = "";
	String FirstTime = "";
	String FirstTimeCarrier = "";
	String FirstTimeVersion = "";
	int IDANTERIOR = 0;
	String ImageCodeMillis;
	String Long = null;
	String Name = "";
	Button NewRecordButton;
	Spinner ProductSpn;
	Spinner ProductSpnNew;
	Spinner VersionSpn;
	Spinner VersionSpnNew;
	ArrayAdapter<String> adapter;
	ArrayAdapter<String> adapterCondition;
	ArrayAdapter<String> adp;
	String avenueCode = "0";
	String avenueDescription = null;
	ImageButton btnAccept;
	Button btnAnterior;
	Button btnCANCELAR;
	Button btnExit;
	Button btnGUARDAR;
	Button btnGUARDARLatLong;
	Button btnProximo;
	Button btnUltimo;
	Button buttonPrimero;
	String condition = "";
	DBHelperVerification db;
	SQLiteDatabase dbBill;
	DatabaseHelper dbHelp;
	String id = null;
	int idForGoBack = 0;
	String imageName = null;
	private ImageView imageView;
	String lat;
	public double latitude;
	List<String> list;
	List<String> listCondition;
	public double longitude;
	String newLatLong = "";
	String newRecord = "";
	String obstraction = "";
	Button photoButton;
	int positionname = 1;
	SharedPreferences prefinsert;
	String prefinsertstr;
	SharedPreferences prefss;
	ListView productlist;
	RadioGroup radioIluminacion;
	RadioGroup radioSaturacion;
	RadioButton radioSaturacionButton;
	RadioButton radioluminacionButton;
	String realCost;
	int selectedPostion = 0;
	Spinner spnCONDITIONS;
	Spinner spnObstruccion;
	String startingPointforDelete = "";
	EditText txtAvisos;
	EditText txtCarrier;
	EditText txtCodigo;
	EditText txtDate;
	EditText txtLat;
	EditText txtLong;
	EditText txtLongFromRF;
	EditText txtObservacion;
	EditText txtOperader;
	AutoCompleteTextView txtProduct;
	AutoCompleteTextView txtProductCode;
	EditText txtSize;
	EditText txtTime;
	EditText txtTotalAvisos;
	AutoCompleteTextView txtVersion;
	AutoCompleteTextView txtVersionCode;
	EditText txtlatFromRf;
	String username = "";

	@SuppressLint("SdCardPath")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainverification);
		prefinsertstr = "update";
		prefinsert = getSharedPreferences("savedData111", MODE_PRIVATE);
		prefinsert.edit().putString("insert", prefinsertstr).commit();
		db = new DBHelperVerification(mainVerification.this);
		SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
		username = prefs.getString("username", "UNKNOWN");
		txtDate = (EditText) findViewById(R.id.txtDate);
		txtTime = (EditText) findViewById(R.id.txtTime);
		txtOperader = (EditText) findViewById(R.id.txtOperader);
		txtLat = (EditText) findViewById(R.id.txtlat);
		txtLong = (EditText) findViewById(R.id.txtLong);
		txtCodigo = (EditText) findViewById(R.id.txtCodigo);
		txtProduct = (AutoCompleteTextView) findViewById(R.id.txtProduct);
		txtProductCode = (AutoCompleteTextView) findViewById(R.id.txtProductCode);
		txtVersionCode = (AutoCompleteTextView) findViewById(R.id.txtVersionCode);
		txtVersion = (AutoCompleteTextView) findViewById(R.id.txtVersion);
		txtCarrier = (EditText) findViewById(R.id.txtCarrier);
		txtSize = (EditText) findViewById(R.id.txtSize);
		txtTotalAvisos = (EditText) findViewById(R.id.txtTotalAvisos);
		txtAvisos = (EditText) findViewById(R.id.txtAvisos);
		txtlatFromRf = (EditText) findViewById(R.id.txtlatFromRf);
		txtLongFromRF = (EditText) findViewById(R.id.txtLongFromRF);
		radioIluminacion = (RadioGroup) findViewById(R.id.radioIluminacion);
		radioSaturacion = (RadioGroup) findViewById(R.id.radioISaturacion);
		spnObstruccion = (Spinner) findViewById(R.id.spnObstruccion);
		spnCONDITIONS = (Spinner) findViewById(R.id.spnCONDITIONS);
		CategorySpnNew = (Spinner) findViewById(R.id.CategorySpnNew);
		ProductSpn = (Spinner) findViewById(R.id.ProductSpn);
		VersionSpn = (Spinner) findViewById(R.id.VersionSpn);
		CarrierSpn = (Spinner) findViewById(R.id.CarrierSpn);
		ProductSpnNew = (Spinner) findViewById(R.id.ProductSpnNew);
		VersionSpnNew = (Spinner) findViewById(R.id.VersionSpnNew);
		this.imageView = (ImageView) this.findViewById(R.id.imageView1);
		photoButton = (Button) this.findViewById(R.id.button1);
		btnExit = (Button) this.findViewById(R.id.btnExit);
		btnAccept = (ImageButton) findViewById(R.id.btnAccept);
		txtObservacion = (EditText) findViewById(R.id.txtObservacion);
		btnProximo = (Button) findViewById(R.id.btnProximo);
		txtCodigo.setText(getIntent().getStringExtra("StartingPoint"));
		Intent intent = getIntent();
		buttonPrimero = (Button) findViewById(R.id.btnPrimero);
		selectedPostion = intent.getIntExtra("position", selectedPostion);
		loadSpinner();
		ProductSpn();
		try {
			dbBill = openOrCreateDatabase("OutdoorAppDB.db",
					SQLiteDatabase.CREATE_IF_NECESSARY, null);
		} catch (SQLException e) {
			Log.d("Error", "Error while Opening Database");
			e.printStackTrace();
		}

		getDataFromBillboard(getIntent().getStringExtra("AvenueName"),
				getIntent().getStringExtra("StartingPoint"));
		photoButton.setOnClickListener(this);
		btnAccept.setOnClickListener(this);
		btnExit.setOnClickListener(this);
		buttonPrimero.setOnClickListener(this);
		btnUltimo = (Button) findViewById(R.id.btnUltimo);
		btnUltimo.setOnClickListener(this);
		btnAnterior = (Button) findViewById(R.id.btnAnterior);
		btnAnterior.setOnClickListener(this);
		btnGUARDARLatLong = (Button) findViewById(R.id.btnGUARDARLatLong);
		btnGUARDARLatLong.setOnClickListener(this);
		btnGUARDAR = (Button) findViewById(R.id.btnGUARDAR);
		btnGUARDAR.setOnClickListener(this);
		btnCANCELAR = (Button) findViewById(R.id.btnCANCELAR);
		btnCANCELAR.setOnClickListener(this);
		NewRecordButton = (Button) findViewById(R.id.btnNuevaValla);
		NewRecordButton.setOnClickListener(this);
		DeleteButton = (Button) findViewById(R.id.btnBorrarValla);
		DeleteButton.setOnClickListener(this);
		btnProximo.setOnClickListener(this);
		ProductSpn.setOnItemSelectedListener(this);
		CarrierSpn.setOnItemSelectedListener(this);
		CategorySpnNew.setOnItemSelectedListener(this);
		ProductSpnNew.setOnItemSelectedListener(this);
		VersionSpnNew.setOnItemSelectedListener(this);
		autocompleteProduct();
		 getValuesFromSatelite();

		txtProduct.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// txtProduct.setTag(null);
				String productCode = db.getProductCode(arg0.getItemAtPosition(
						arg2).toString());
				txtProductCode.setText(productCode);

				Toast.makeText(getApplicationContext(),
						arg0.getItemAtPosition(arg2).toString(), 2000).show();
			}
		});
		txtVersion.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// txtProduct.setTag(null);
				String versionCode = db.getVersionCode(arg0.getItemAtPosition(
						arg2).toString());
				txtVersionCode.setText(versionCode);

				// Toast.makeText(getApplicationContext(),versionCode,
				// 2000).show();
			}
		});
		txtProductCode.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// txtProduct.setTag(null);
				String product = db.getProduct(arg0.getItemAtPosition(arg2)
						.toString());
				txtProduct.setText(product);

				// Toast.makeText(getApplicationContext(),versionCode,
				// 2000).show();
			}
		});

		txtVersionCode.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// txtProduct.setTag(null);
				String version = db.getVersion(arg0.getItemAtPosition(arg2)
						.toString());
				txtVersion.setText(version);

				// Toast.makeText(getApplicationContext(),versionCode,
				// 2000).show();
			}
		});
	}

	@SuppressLint("SdCardPath")
	private void getDataFromBillboard(String avnuename, String startingpointName) {
		Cursor cur3 = dbBill.rawQuery(
				"select * from tblAvenue where AvenueDescription='" + avnuename
						+ "'", null);
		cur3.moveToFirst();
		// String avenueCode = "0";
		while (!cur3.isAfterLast()) { // txtProduct.setText(cur3.getString(1));
			avenueCode = cur3.getString(1);
			cur3.moveToNext();
		}
		cur3.close();
		Cursor c = dbBill.rawQuery("SELECT * FROM tblBillboard where Avenue="
				+ avenueCode + " and Betweenavenue like '%" + startingpointName
				+ "%'", null);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			avenueCode = c.getString(1);
			txtProduct.setText(c.getString(30).toString().replace("\"", ""));
			txtProductCode
					.setText(c.getString(29).toString().replace("\"", ""));
			txtVersionCode
					.setText(c.getString(18).toString().replace("\"", ""));
			txtVersion.setText(c.getString(19).toString().replace("\"", ""));
			txtCarrier.setText(c.getString(7).toString().replace("\"", ""));
			txtSize.setText(c.getString(5).toString().replace("\"", ""));
			txtTotalAvisos
					.setText(c.getString(12).toString().replace("\"", ""));
			txtAvisos.setText(c.getString(11).toString().replace("\"", ""));
			realCost = c.getString(9).toString().replace("\"", "");
			imageName = c.getString(33).toString().replace("\"", "");
			id = c.getString(0).toString().replace("\"", "");
			// line=c.getString(28);
			String[] rowData = null;
			rowData = c.getString(10).toString().split("/");
			txtlatFromRf.setText(rowData[0]);
			txtLongFromRF.setText(rowData[1]);
			AvenueCodeMain = c.getString(1);
			c.moveToNext();

		}

		c.close();
		Cursor cur = dbBill.rawQuery(
				"SELECT count(Avenue) as count FROM tblBillboard WHERE Avenue = "
						+ avenueCode, null);
		cur.moveToFirst();
		int icount = cur.getInt(0);
		txtTotalAvisos.setText(String.valueOf(icount));
		cur.close();
		File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/" + imageName
				+ ".jpg");
		if (imgFile.exists()) {
			// Toast.makeText(getApplicationContext(),
			// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
			// 30000).show();
			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
					.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		} else {
			File noImg = new File(
					"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
			Bitmap myBitmap = BitmapFactory.decodeFile(noImg.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		}

	}

	public void getValuesFromSatelite() {
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		txtDate.setText(sdf.format(new Date()));
		Date d = new Date();
		String time = d.getHours() + ":" + d.getMinutes();
		txtTime.setText(time);
		txtOperader.setText(username);
		LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		LocationListener mlocListener = new MyLocationListener();
		mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
				0, mlocListener);
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				mlocListener);
	}

	private String[] getProduct(String str) {
		Cursor c;

		c = dbBill.rawQuery("select * from tblAvenue Where AvenueDescription='"
				+ str + "'", null);
		c.moveToFirst();
		String AvenueCode = null;

		if (c.moveToFirst()) {
			do {
				AvenueCode = c.getString(1);
				// set.add(cursor.getString(2));
			} while (c.moveToNext());
		}
		Cursor cur = null;
		cur = dbBill.rawQuery("SELECT * FROM tblbillboard where avenue="
				+ AvenueCode, null);

		String[] strr = new String[cur.getCount()];
		int i = 0;
		if (cur.moveToFirst()) {
			do {
				strr[i] = cur.getString(30);
				i++;
			} while (cur.moveToNext());
		}
		cur.close();
		return strr;

	}

	public void getFirstData(String str, String buttonclick) {
		Cursor c;

		c = dbBill.rawQuery("select * from tblAvenue Where AvenueDescription='"
				+ str + "'", null);
		c.moveToFirst();
		String AvenueCode = null;

		if (c.moveToFirst()) {
			do {
				AvenueCode = c.getString(1);
				// set.add(cursor.getString(2));
			} while (c.moveToNext());
		}
		Cursor cur = null;
		if (buttonclick.equals("Primero")) {
			cur = dbBill.rawQuery(
					"SELECT *,min(id) FROM tblbillboard where avenue="
							+ AvenueCode, null);
		} else if (buttonclick.equals("Ultimo")) {
			cur = dbBill.rawQuery(
					"SELECT *,max(id) FROM tblbillboard where avenue="
							+ AvenueCode, null);

		} else if (buttonclick.equals("Anterior")) {
			int ID = Integer.parseInt(id) - 1;
			cur = dbBill.rawQuery("SELECT * FROM tblbillboard where id=" + ID,
					null);

		} else if (buttonclick.equals("Salvar")) {
			int ID = Integer.parseInt(id) + 1;
			cur = dbBill.rawQuery("SELECT * FROM tblbillboard where id=" + ID,
					null);
		}
		if (cur.moveToFirst()) {
			do {
				txtProduct.setText(cur.getString(30).toString()
						.replace("\"", ""));
				txtProductCode.setText(cur.getString(29).toString()
						.replace("\"", ""));
				txtVersionCode.setText(cur.getString(18).toString()
						.replace("\"", ""));
				txtVersion.setText(cur.getString(19).toString()
						.replace("\"", ""));
				txtCarrier.setText(cur.getString(7).toString()
						.replace("\"", ""));
				txtSize.setText(cur.getString(5).toString().replace("\"", ""));
				txtTotalAvisos.setText(cur.getString(12).toString()
						.replace("\"", ""));
				txtAvisos.setText(cur.getString(11).toString()
						.replace("\"", ""));
				realCost = cur.getString(9).toString().replace("\"", "");
				imageName = cur.getString(33).toString().replace("\"", "");
				id = cur.getString(0).toString().replace("\"", "");
				String startingPoint = null;
				startingPoint = cur.getString(28);
				String[] rowData = null;
				rowData = startingPoint.split(" ");
				txtCodigo.setText(rowData[0]);
				// Toast.makeText(getApplicationContext(),
				// c.getString(10).toString(), 20000).show();
				String[] rowData1 = null;
				rowData1 = cur.getString(10).toString().split("/");
				txtlatFromRf.setText(rowData1[0]);
				txtLongFromRF.setText(rowData1[1]);
			} while (c.moveToNext());
		}
		cur.close();
		c.close();
		File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/" + imageName
				+ ".jpg");
		if (imgFile.exists()) {

			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
					.getAbsolutePath());
			imageView.setImageBitmap(myBitmap);
		} else {
			File noImg = new File(
					"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
			Bitmap myBitmap = BitmapFactory.decodeFile(noImg.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		}
		positionname = Integer.parseInt(id) + 1;

	}

	private void loadSpinner() {
		// here i used Set Because Set doesn't allow duplicates.
		Set<String> set = db.getAllData();

		List<String> list = new ArrayList<String>(set);

		adapter = new ArrayAdapter<String>(mainVerification.this,
				android.R.layout.simple_spinner_item, list);

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spnObstruccion.setAdapter(adapter);
		spnObstruccion.setWillNotDraw(false);
		Set<String> setCondition = db.getAllDataOfCondition();

		List<String> listCondition = new ArrayList<String>(setCondition);

		adapterCondition = new ArrayAdapter<String>(mainVerification.this,
				android.R.layout.simple_spinner_item, listCondition);
		adapterCondition
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnCONDITIONS.setAdapter(adapterCondition);
		spnCONDITIONS.setWillNotDraw(false);

		Set<String> setCategory = db.getAllData1();
		List<String> listCategory = new ArrayList<String>(setCategory);
		Collections.sort(listCategory);
		listCategory.add(0, "--Select One--");
		ArrayAdapter<String> adpCategory = new ArrayAdapter<String>(
				mainVerification.this,
				android.R.layout.simple_spinner_dropdown_item, listCategory);
		adpCategory
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		CategorySpnNew.setAdapter(adpCategory);
		CategorySpnNew.setWillNotDraw(false);

	}

	private void ProductSpn() {
		Set<String> set = db.getAllProduct();
		List<String> listProduct = new ArrayList<String>(set);
		Collections.sort(listProduct);
		adapter = new ArrayAdapter<String>(mainVerification.this,
				android.R.layout.simple_spinner_dropdown_item, listProduct);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		ProductSpn.setAdapter(adapter);
		ProductSpn.setWillNotDraw(false);
		Set<String> setCarrier = db.getAllCarrier();
		List<String> listCarrier = new ArrayList<String>(setCarrier);
		Collections.sort(listCarrier);
		adapter = new ArrayAdapter<String>(mainVerification.this,
				android.R.layout.simple_spinner_dropdown_item, listCarrier);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		CarrierSpn.setAdapter(adapter);
		CarrierSpn.setWillNotDraw(false);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			Intent cameraIntent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(cameraIntent, CAMERA_REQUEST);
			// txtProduct.setText("");
			txtProductCode.setText("");
			txtVersion.setText("");
			txtVersionCode.setText("");

			break;
		case R.id.btnAccept:
			insert("True");
			prefinsertstr = prefinsert.getString("insert", prefinsertstr);
			update(Name);
			positionname = selectedPostion + positionname;
			getNewValues1(avenueCode);
			getValuesFromSatelite();
			if (Name.equals("New")) {
				this.dbBill
						.execSQL("create table IF NOT EXISTS tblNewProduct (ID INTEGER PRIMARY KEY,Avenue  TEXT,Product VARCHAR,Version VARCHAR);");
				this.dbBill
						.execSQL("Insert into tblNewProduct (Avenue,Product,Version) values( '"
								+ this.avenueCode
								+ "','"
								+ this.txtProductCode.getText()
								+ "','"
								+ this.txtVersionCode.getText() + "');");
			}
			this.FirstTime = "FirstTime";
			this.FirstTimeVersion = "FirstTime";
			this.FirstTimeCarrier = "FirstTime";
			this.ANTERIOR = "ANTERIOR";
			this.FirstCategory = "";
			this.Name = "";
			FirstNewProduct = "";
			FirstNewVersion = "";
			break;
		case R.id.btnExit:
			Intent localIntent2 = new Intent(this, Verification.class);
			startActivity(localIntent2);
			break;
		case R.id.btnPrimero:
			getValuesFromSatelite();
			primeRecord();
			ProductSpn();
			loadSpinner();
			this.FirstTime = "FirstTime";
			this.FirstTimeVersion = "FirstTime";
			this.FirstTimeCarrier = "FirstTime";
			this.FirstCategory = "";
			this.Name = "";
			this.ANTERIOR = "ANTERIOR";
			FirstNewProduct = "";
			FirstNewVersion = "";
			break;
		case R.id.btnUltimo:
			getValuesFromSatelite();
			ProductSpn();
			ultino(avenueCode);
			loadSpinner();
			this.FirstTime = "FirstTime";
			this.FirstTimeVersion = "FirstTime";
			this.FirstTimeCarrier = "FirstTime";
			this.FirstCategory = "";
			this.Name = "";
			this.ANTERIOR = "ANTERIOR";
			FirstNewProduct = "";
			FirstNewVersion = "";
			break;
		case R.id.btnAnterior:
			forANTERIOR(this.ANTERIOR);
			getValuesFromSatelite();
			ProductSpn();
			loadSpinner();
			this.FirstTime = "FirstTime";
			this.FirstTimeVersion = "FirstTime";
			this.FirstTimeCarrier = "FirstTime";
			this.FirstCategory = "";
			this.Name = "";
			this.ANTERIOR = "";
			FirstNewProduct = "";
			FirstNewVersion = "";
			Toast.makeText(getApplicationContext(), imageName, 20000).show();
			break;
		case R.id.btnNuevaValla:
			String str5 = String.valueOf(txtCodigo.getText());
			//forNewStartingPoint(str5);

			clearFields();
			getValuesFromSatelite();

			Intent cameraIntent1 = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(cameraIntent1, CAMERA_REQUEST);

			loadSpinner();
			String str6 = this.db.ProductForNewRecord();
			String str7 = this.db.VersionForNewRecord();
			this.txtProductCode.setText(str6);
			this.txtVersionCode.setText(str7);
			this.FirstTime = "FirstTime";
			this.FirstTimeVersion = "FirstTime";
			this.FirstTimeCarrier = "FirstTime";
			this.FirstCategory = "";
			this.Name = "New";
			this.newRecord = "newRecord";
			this.ANTERIOR = "ANTERIOR";
			FirstNewProduct = "";
			FirstNewVersion = "";
			if (str5.contains("-")) {
				contain(str5);

			} else {
				forNewStartingPoint(str5);
			}
			// ProductSpn();
			break;
		case R.id.btnBorrarValla:
			final int ID = Integer.parseInt(id);
			DialogInterface.OnClickListener dialogClickListener1 = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						startingPointforDelete = String.valueOf(txtCodigo
								.getText());
						dbBill.execSQL("Delete from tblBillboard where id="
								+ ID);
						DeleteRecord(startingPointforDelete, avenueCode);
						// getValuesFromSatelite();
						Toast.makeText(getBaseContext(),
								"Records are deleted successfully",
								Toast.LENGTH_SHORT).show();
						break;

					case DialogInterface.BUTTON_NEGATIVE:
						// No button clicked
						break;
					}
				}
			};

			AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
			builder1.setMessage("Are you sure you want to delete?")
					.setPositiveButton("Yes", dialogClickListener1)
					.setNegativeButton("No", dialogClickListener1).show();
			getValuesFromSatelite();
			ProductSpn();
			loadSpinner();
			this.Name = "";
			this.ANTERIOR = "ANTERIOR";
			break;
		case R.id.btnProximo:

			Set<String> set = db.getStartingPointList(avenueCode);
			List<String> nonu = new ArrayList<String>(set);
			Collections.sort(nonu);
			String str = String.valueOf(nonu.size());
			// Toast.makeText(getApplicationContext(), str, 2000).show();
			int j = 0;
			for (int i = 0; i < nonu.size(); i++) {
				String newPoint = nonu.get(i);
				String oldPoint = String.valueOf(txtCodigo.getText());
				// Toast.makeText(getApplicationContext(),nonu.get(i),
				// 20000).show();
				if (newPoint.equals(oldPoint)) {
					// Toast.makeText(getApplicationContext(),oldPoint,
					// 2000).show();
					j = i + 1;
					break;
				}

			}
			if (j == nonu.size()) {
				Toast.makeText(getApplicationContext(),
						"it's the last record for the avenue.", 20000).show();
			}
			insert("True");
			update(prefinsertstr);
			getNewValues1(avenueCode);
			getValuesFromSatelite();
			this.FirstTime = "FirstTime";
			this.FirstTimeVersion = "FirstTime";
			this.FirstTimeCarrier = "FirstTime";
			this.FirstCategory = "";
			this.Name = "";
			this.ANTERIOR = "ANTERIOR";
			FirstNewProduct = "";
			FirstNewVersion = "";
			break;
		case R.id.btnGUARDARLatLong:
			final myDBForProduct myDb = new myDBForProduct(this);
			long saveStatus = myDb.updateLatLongOnly(txtLat.getText()
					.toString(), txtLong.getText().toString(), String
					.valueOf(id));
			break;
		case R.id.btnGUARDAR:
			saveDataInhistoryTable();
			update("");
			break;
		default:
			break;
		}

	}

	private void clearFields() {
		this.txtAvisos.setText("");
		this.txtCarrier.setText("");
		this.txtObservacion.setText("");
		this.txtProduct.setText("");
		this.txtProductCode.setText("");
		this.txtSize.setText("");
		this.txtTotalAvisos.setText("");
		this.txtVersion.setText("");
		this.txtVersionCode.setText("");
		this.txtlatFromRf.setText("");
		this.txtLongFromRF.setText("");
		Bitmap localBitmap = BitmapFactory.decodeFile(new File(
				"/mnt/sdcard/Images/Outdoor/image/noimage.jpg")
				.getAbsolutePath());
		this.imageView.setImageBitmap(localBitmap);

	}

	public void insert(String paramString) {
		int i = this.radioSaturacion.getCheckedRadioButtonId();
		this.radioluminacionButton = ((RadioButton) findViewById(this.radioIluminacion
				.getCheckedRadioButtonId()));
		this.radioSaturacionButton = ((RadioButton) findViewById(i));
		this.dbBill = openOrCreateDatabase(DBNAME, 0, null);
		this.dbBill
				.execSQL("CREATE TABLE IF NOT EXISTS tblBillboardOutput(ID INTEGER PRIMARY KEY , Date INTEGER,Time VARCHAR,StartingPoint VARCHAR,Carrier VARCHAR,Size VARCHAR,Product VARCHAR,ProductCode VARCHAR,Version VARCHAR,VersionCode VARCHAR,Condition VARCHAR,Obstraction VARCHAR,NumberofAdd VARCHAR,TotalNumberOfadd VARCHAR,Iluminacion VARCHAR,Saturacion VARCHAR,Latitud VARCHAR,Longitud VARCHAR,ImageCode VARCHAR,Operator VARCHAR,RealCost VARCHAR,Verified VARCHAR,Observacion VARCHAR,avenue VARCHAR); ");
		deleteRecordIfExist(this.txtCodigo.getText().toString());
		this.dbBill
				.execSQL("INSERT INTO tblBillboardOutput (Date,Time,StartingPoint,Carrier,Size,Product,ProductCode,Version,VersionCode,Condition,Obstraction,NumberofAdd,TotalNumberOfadd,Iluminacion,Saturacion,Latitud,Longitud,ImageCode,Operator,RealCost,Verified,Observacion,avenue) VALUES ('"
						+ this.txtDate.getText().toString()
						+ "','"
						+ this.txtTime.getText().toString()
						+ "','"
						+ this.txtCodigo.getText().toString()
						+ "','"
						+ this.txtCarrier.getText()
						+ "',"
						+ "'"
						+ this.txtSize.getText().toString()
						+ "','"
						+ this.txtProduct.getText()
						+ "','"
						+ this.txtProductCode.getText().toString()
						+ "','"
						+ this.txtVersion.getText()
						+ "','"
						+ this.txtVersionCode.getText().toString()
						+ "','"
						+ this.spnCONDITIONS.getSelectedItem().toString()
						+ "','"
						+ this.spnObstruccion.getSelectedItem().toString()
						+ "','"
						+ this.txtAvisos.getText().toString()
						+ "','"
						+ this.txtTotalAvisos.getText().toString()
						+ "','"
						+ this.radioluminacionButton.getText()
						+ "','"
						+ this.radioSaturacionButton.getText()
						+ "','','','"
						+ this.imageName
						+ "','"
						+ this.txtOperader.getText().toString()
						+ "','"
						+ this.realCost
						+ "','"
						+ paramString
						+ "','"
						+ this.txtObservacion.getText().toString().trim()
						+ "','" + this.avenueCode + "');");
		Toast.makeText(getBaseContext(), "Saved Successfully...", 0).show();
		this.txtObservacion.setText("");
	}

	protected void deleteRecordIfExist(String paramString) {
		Cursor localCursor = this.dbBill.rawQuery(
				"select * from tblBillboardOutput Where Avenue='"
						+ this.avenueCode + "' and StartingPoint='"
						+ paramString + "'", null);
		localCursor.moveToFirst();
		if (localCursor.getCount() >= 1) {
			String str = "DELETE FROM tblBillboardOutput WHERE  Avenue='"
					+ this.avenueCode + "' and StartingPoint='" + paramString
					+ "'";
			this.dbBill.execSQL(str);
		}
	}

	public void update(String str) {
		// new Class DB
		this.dbBill
				.execSQL("create table IF NOT EXISTS tblANTERIOR (ID INTEGER PRIMARY KEY,Avenue  VARCHAR,BillboardID VARCHAR);");
		if (str.equals("")) {
			final myDBForProduct myDb = new myDBForProduct(this);
			final AlertDialog.Builder adb = new AlertDialog.Builder(this);
			AlertDialog ad = adb.create();
			if (this.newLatLong.equals("newLatLong")) {
				this.lat = this.txtLat.getText().toString();
				Long = this.txtLong.getText().toString();
			}

			else {
				this.lat = this.txtlatFromRf.getText().toString();
				Long = this.txtLongFromRF.getText().toString();

			}
			// Save Data
			long saveStatus = myDb.updateDateAfterVerification(imageName,
					txtProductCode.getText().toString(), txtProduct.getText()
							.toString(), txtSize.getText().toString(),
					txtCarrier.getText().toString(), txtAvisos.getText()
							.toString(), txtTotalAvisos.getText().toString(),
					txtVersionCode.getText().toString(), txtVersion.getText()
							.toString(), id, lat + "/" + Long, txtDate
							.getText().toString());
		} else {
			this.dbBill
					.execSQL("INSERT INTO tblBillboard (Avenue,Date,Starttime,Endtime,Size,Carrier,CarrierDescription,Quality,RealCost,LatandLong,Numberofads,Totaladsinthatlocation,typeofads,Visibilitycode,Visibilitydescription,Verificationdate,Verificationdescription,Versiocode,Versiondescription,Productcode,Constant,CategoryCode,Categorydescription,Subsectorcode,Subsectordescription,Sectorcode,Sectordescription,Betweenavenue,Brandcode,Branddescription,Announcercode,Announcerdescription,Imagecode,Agencycode,Agencyname,Condition,Obstruction) VALUES ("
							+ this.AvenueCodeMain
							+ ",'"
							+ this.txtDate.getText().toString()
							+ "','"
							+ this.txtTime.getText().toString()
							+ "','"
							+ "','"
							+ this.txtSize.getText().toString()
							+ "','"
							+ "','"
							+ this.txtCarrier.getText().toString()
							+ "','"
							+ "','"
							+ "','"
							+ this.txtLat.getText().toString()
							+ "/"
							+ this.txtLong.getText().toString()
							+ "','"
							+ this.txtAvisos.getText().toString()
							+ "','"
							+ this.txtTotalAvisos.getText().toString()
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ this.txtVersionCode.getText()
							+ "','"
							+ this.txtVersion.getText().toString()
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ "','"
							+ this.txtCodigo.getText().toString()
							+ "','"
							+ this.txtProductCode.getText().toString()
							+ "','"
							+ this.txtProduct.getText().toString()
							+ "','"
							+ "','"
							+ "','"
							+ imageName
							+ "','','',"
							+ "'"
							+ this.spnCONDITIONS.getSelectedItem().toString()
							+ "','"
							+ this.spnObstruccion.getSelectedItem().toString()
							+ "');");
		}

		this.Name = "";
		this.idForGoBack = this.db.lastID();
		this.dbBill
				.execSQL("INSERT INTO tblANTERIOR  (Avenue,BillboardID)  VALUES ('"
						+ this.AvenueCodeMain
						+ "','"
						+ this.idForGoBack
						+ "');");

		// + "" + "','" + rowData[34] + "');");

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			// photo.
			imageView.setImageBitmap(photo);
			saveToSD(photo);
		}

	}

	public void saveToSD(Bitmap outputImage) {

		String name = prefinsert.getString("insert", prefinsertstr);
		File storagePath = new File(Environment.getExternalStorageDirectory()
				+ "/Images/Outdoor/image/");
		storagePath.mkdirs();
		File storagePath2 = new File(Environment.getExternalStorageDirectory()
				+ "/Images/Outdoor/NewImages/");

		ImageCodeMillis = this.db.ImageForNewRecord(String
				.valueOf(this.avenueCode));
		File myImage = null;
		File newImage = null;
		imageName = ImageCodeMillis;
		myImage = new File(storagePath, ImageCodeMillis + ".jpg");
		newImage = new File(storagePath2, ImageCodeMillis + ".jpg");
		try {
			FileOutputStream out = new FileOutputStream(myImage);
			FileOutputStream out2 = new FileOutputStream(newImage);
			outputImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
			outputImage.compress(Bitmap.CompressFormat.JPEG, 80, out2);
			out.flush();
			out.close();
			out2.flush();
			out2.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		String[] countries = getProduct(getIntent()
				.getStringExtra("AvenueName"));
		for (int i = 0; i < countries.length; i++) {

			Log.i(this.toString(), countries[i]);
		}
		txtProduct.setText("");
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.list_item, countries);
		txtProduct.setAdapter(adapter);
		newLatLong = "newLatLong";
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		// TODO Auto-generated method stub
		switch (parent.getId()) {
		case R.id.ProductSpn:
			if (FirstTime != "") {
				String productCode = db.getProductCode(parent
						.getItemAtPosition(position).toString());
				txtProductCode.setText(productCode);

			}
			Set<String> setVersion = db.getAllVersion(parent.getItemAtPosition(
					position).toString());
			List<String> listVersion = new ArrayList<String>(setVersion);
			Collections.sort(listVersion);
			adapter = new ArrayAdapter<String>(mainVerification.this,
					android.R.layout.simple_spinner_dropdown_item, listVersion);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			VersionSpn.setAdapter(adapter);
			VersionSpn.setWillNotCacheDrawing(false);
			FirstTime = "FirstTime";

			break;
		case R.id.CarrierSpn:
			txtCarrier.setText(parent.getItemAtPosition(position).toString());
			break;
		case R.id.CategorySpnNew:
			if (FirstCategory != "") {
				Set<String> setCategory = db.getAllProductByCategory(parent
						.getItemAtPosition(position).toString());
				List<String> listCategory = new ArrayList<String>(setCategory);
				Collections.sort(listCategory);
				listCategory.add(0, "--Select One--");
				adapter = new ArrayAdapter<String>(mainVerification.this,
						android.R.layout.simple_spinner_dropdown_item,
						listCategory);

				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				ProductSpnNew.setAdapter(adapter);

				ProductSpnNew.setWillNotCacheDrawing(false);
				FirstNewProduct = "FirstNewProduct";

				/*
				 * Set<String> setCode =
				 * db.getAllVersionByCategory(parent.getItemAtPosition(
				 * position).toString()); List<String> listCode = new
				 * ArrayList<String>(setCode); Collections.sort(list);
				 * ArrayAdapter<String> adapterCode = new
				 * ArrayAdapter<String>(this,
				 * android.R.layout.simple_dropdown_item_1line, listCode);
				 * txtProduct.setAdapter(adapterCode);
				 */
			}

			FirstCategory = "FirstCategory";
			break;
		case R.id.ProductSpnNew:
			if (FirstNewProduct != "") {

				Set<String> setProduct = db.getAllVersionByCategory(parent
						.getItemAtPosition(position).toString());
				List<String> listCategoryVersion = new ArrayList<String>(
						setProduct);
				Collections.sort(listCategoryVersion);
				listCategoryVersion.add(0, "--Select One--");
				adapter = new ArrayAdapter<String>(mainVerification.this,
						android.R.layout.simple_spinner_dropdown_item,
						listCategoryVersion);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				VersionSpnNew.setAdapter(adapter);
				VersionSpnNew.setWillNotCacheDrawing(false);
				txtProduct.setText(parent.getItemAtPosition(position)
						.toString());
				txtProductCode.setText(db.getAllProductCodeByCategory(parent
						.getItemAtPosition(position).toString()));
				FirstNewVersion = "FirstNewVersion";

			}

			break;
		case R.id.VersionSpnNew:
			if (FirstNewProduct != "") {
				txtVersion.setText(parent.getItemAtPosition(position)
						.toString());
				txtVersionCode.setText(db.getAllVersionCodeByCategory(parent
						.getItemAtPosition(position).toString()));
			}

			break;
		}
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	public class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			latitude = location.getLatitude();
			longitude = location.getLongitude();
			txtLat.setText(latitude + "");
			txtLong.setText(longitude + "");
		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Disabled",
					Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Enabled",
					Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}
	}

	public void autocompleteProduct() {
		Set<String> set = db.getAllProduct();
		List<String> list = new ArrayList<String>(set);
		Collections.sort(list);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, list);
		txtProduct.setAdapter(adapter);

		Set<String> setVersion = db.getAllVersion(txtProduct.getText()
				.toString());
		List<String> listVersion = new ArrayList<String>(setVersion);
		Collections.sort(listVersion);
		ArrayAdapter<String> adapterVersion = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, listVersion);
		txtVersion.setAdapter(adapterVersion);

		Set<String> setProductCode = db.getAllProductCode();
		List<String> listProductCode = new ArrayList<String>(setProductCode);
		Collections.sort(listProductCode);
		ArrayAdapter<String> adapterProductCode = new ArrayAdapter<String>(
				this, android.R.layout.simple_dropdown_item_1line,
				listProductCode);
		txtProductCode.setAdapter(adapterProductCode);

		Set<String> setVersionCode = db.getAllVersionCode(txtProductCode
				.getText().toString());
		List<String> listVersionCode = new ArrayList<String>(setVersionCode);
		Collections.sort(listVersionCode);
		ArrayAdapter<String> adapterVersionCode = new ArrayAdapter<String>(
				this, android.R.layout.simple_dropdown_item_1line,
				listVersionCode);
		txtVersionCode.setAdapter(adapterVersionCode);
	}

	private static enum containStartingPoint {
		A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z;
	}

	protected void forANTERIOR(String paramString) {
		if (paramString.equals("ANTERIOR")) {
			Cursor cur = this.dbBill.rawQuery(
					"SELECT MAX(ID), BillboardID FROM tblANTERIOR", null);
			Toast.makeText(getApplicationContext(),
					String.valueOf(cur.getCount()), 20000).show();
			if (cur.getCount() != 0) {
				cur.moveToFirst();
				while (!cur.isAfterLast()) {
					IDANTERIOR = Integer.parseInt(cur.getString(0));
					id = cur.getString(1);
					Toast.makeText(getApplicationContext(),
							String.valueOf(IDANTERIOR), 20000).show();
					cur.moveToNext();
				}
				cur.close();
				Cursor c = dbBill.rawQuery(
						"select * from tblBillboard Where ID='"
								+ this.id + "'", null);
				c.moveToFirst();
				while (!c.isAfterLast()) {
					avenueCode = c.getString(1);
					txtProduct.setText(c.getString(30).toString()
							.replace("\"", ""));
					txtProductCode.setText(c.getString(29).toString()
							.replace("\"", ""));
					txtVersionCode.setText(c.getString(18).toString()
							.replace("\"", ""));
					txtVersion.setText(c.getString(19).toString()
							.replace("\"", ""));
					txtCarrier.setText(c.getString(7).toString()
							.replace("\"", ""));
					txtSize.setText(c.getString(5).toString().replace("\"", ""));
					txtTotalAvisos.setText(c.getString(12).toString()
							.replace("\"", ""));
					txtAvisos.setText(c.getString(11).toString()
							.replace("\"", ""));
					realCost = c.getString(9).toString().replace("\"", "");
					imageName = c.getString(33).toString().replace("\"", "");
					id = c.getString(0).toString().replace("\"", "");
					String startingPoint = null;
					startingPoint = c.getString(28).replace("\"", "");
					String[] rowData = null;
					rowData = startingPoint.split(" ");
					txtCodigo.setText(rowData[0]);
					// String[] rowData1 = null;
					// rowData1 = c.getString(10).toString().split("/");
					// txtlatFromRf.setText(rowData1[0]);
					// txtLongFromRF.setText(rowData[1]);
					c.moveToNext();
				}
				c.close();

				File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/"
						+ imageName + ".jpg");
				if (imgFile.exists()) {
					// Toast.makeText(getApplicationContext(),
					// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
					// 30000).show();
					Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
							.getAbsolutePath());

					imageView.setImageBitmap(myBitmap);
				} else {
					File noImg = new File(
							"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
					Bitmap myBitmap = BitmapFactory.decodeFile(noImg
							.getAbsolutePath());

					imageView.setImageBitmap(myBitmap);
				}
			} else {
				Toast.makeText(getApplicationContext(), "No Record Found",
						20000).show();
			}
		} else {
			IDANTERIOR = IDANTERIOR - 1;
			// localCursor1 =
			// this.dbBill.rawQuery("SELECT ID, BillboardID FROM tblANTERIOR where id="
			// + this.IDANTERIOR, null))
			Cursor cur = this.dbBill.rawQuery(
					"SELECT ID, BillboardID FROM tblANTERIOR where id="
							+ this.IDANTERIOR, null);
			Toast.makeText(getApplicationContext(),
					String.valueOf(cur.getCount()), 20000).show();
			if (cur.getCount() != 0) {
				cur.moveToFirst();
				while (!cur.isAfterLast()) {
					// IDANTERIOR=Integer.parseInt(cur.getString(0));
					id = cur.getString(1);
					cur.moveToNext();
				}
				cur.close();
				Cursor c = dbBill.rawQuery(
						"select * from tblBillboard Where ID='"
								+ this.id + "'", null);
				c.moveToFirst();
				while (!c.isAfterLast()) {
					avenueCode = c.getString(1);
					txtProduct.setText(c.getString(30).toString()
							.replace("\"", ""));
					txtProductCode.setText(c.getString(29).toString()
							.replace("\"", ""));
					txtVersionCode.setText(c.getString(18).toString()
							.replace("\"", ""));
					txtVersion.setText(c.getString(19).toString()
							.replace("\"", ""));
					txtCarrier.setText(c.getString(7).toString()
							.replace("\"", ""));
					txtSize.setText(c.getString(5).toString().replace("\"", ""));
					txtTotalAvisos.setText(c.getString(12).toString()
							.replace("\"", ""));
					txtAvisos.setText(c.getString(11).toString()
							.replace("\"", ""));
					realCost = c.getString(9).toString().replace("\"", "");
					imageName = c.getString(33).toString().replace("\"", "");
					id = c.getString(0).toString().replace("\"", "");
					String startingPoint = null;
					startingPoint = c.getString(28).replace("\"", "");
					String[] rowData = null;
					rowData = startingPoint.split(" ");
					txtCodigo.setText(rowData[0]);
					// String[] rowData1 = null;
					// rowData1 = c.getString(10).toString().split("/");
					// txtlatFromRf.setText(rowData1[0]);
					// txtLongFromRF.setText(rowData[1]);
					c.moveToNext();
				}
				c.close();

				File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/"
						+ imageName + ".jpg");
				if (imgFile.exists()) {
					// Toast.makeText(getApplicationContext(),
					// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
					// 30000).show();
					Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
							.getAbsolutePath());

					imageView.setImageBitmap(myBitmap);
				} else {
					File noImg = new File(
							"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
					Bitmap myBitmap = BitmapFactory.decodeFile(noImg
							.getAbsolutePath());

					imageView.setImageBitmap(myBitmap);
				}
			} else {
				Toast.makeText(getApplicationContext(), "No Record Found",
						20000).show();
			}

		}
	}

	private void getNewValues1(String paramInt) {
		Set<String> set = db.getStartingPointList(paramInt);
		List<String> nonu = new ArrayList<String>(set);
		Collections.sort(nonu);
		String str = String.valueOf(nonu.size());
		// Toast.makeText(getApplicationContext(), str, 2000).show();
		int j = 0;
		for (int i = 0; i < nonu.size(); i++) {
			String newPoint = nonu.get(i);
			String oldPoint = String.valueOf(txtCodigo.getText());
			// Toast.makeText(getApplicationContext(),nonu.get(i),
			// 20000).show();
			if (newPoint.equals(oldPoint)) {
				// Toast.makeText(getApplicationContext(),oldPoint,
				// 2000).show();
				j = i + 1;
				break;
			}

		}
		// Toast.makeText(getApplicationContext(),nonu.get(j), 20000).show();
		String selectQuery = "Select * from tblBillboard where  Avenue = "
				+ paramInt + " and Betweenavenue  like '%" + nonu.get(j)
				+ "%' limit 1";
		Cursor c = dbBill.rawQuery(selectQuery, null);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			avenueCode = c.getString(1);
			txtProduct.setText(c.getString(30).toString().replace("\"", ""));
			txtProductCode
					.setText(c.getString(29).toString().replace("\"", ""));
			txtVersionCode
					.setText(c.getString(18).toString().replace("\"", ""));
			txtVersion.setText(c.getString(19).toString().replace("\"", ""));
			txtCarrier.setText(c.getString(7).toString().replace("\"", ""));
			txtSize.setText(c.getString(5).toString().replace("\"", ""));
			txtTotalAvisos
					.setText(c.getString(12).toString().replace("\"", ""));
			txtAvisos.setText(c.getString(11).toString().replace("\"", ""));
			realCost = c.getString(9).toString().replace("\"", "");
			imageName = c.getString(33).toString().replace("\"", "");
			id = c.getString(0).toString().replace("\"", "");
			String startingPoint = null;
			startingPoint = c.getString(28).replace("\"", "");
			String[] rowData = null;
			rowData = startingPoint.split(" ");
			txtCodigo.setText(rowData[0]);
			String[] rowData1 = null;
			rowData1 = c.getString(10).toString().split("/");
			txtlatFromRf.setText(rowData1[0]);
			txtLongFromRF.setText(rowData1[1]);
			c.moveToNext();
		}
		c.close();
		Cursor cur = dbBill.rawQuery(
				"SELECT count(Avenue) as count FROM tblBillboard WHERE Avenue = "
						+ avenueCode, null);
		cur.moveToFirst();
		int icount = cur.getInt(0);
		txtTotalAvisos.setText(String.valueOf(icount));
		cur.close();
		File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/" + imageName
				+ ".jpg");
		if (imgFile.exists()) {
			// Toast.makeText(getApplicationContext(),
			// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
			// 30000).show();
			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
					.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		} else {
			File noImg = new File(
					"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
			Bitmap myBitmap = BitmapFactory.decodeFile(noImg.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		}
	}

	protected void primeRecord() {
		Cursor c = this.dbBill.rawQuery(
				"select * from tblBillboard Where Avenue='" + this.avenueCode
						+ "' order by Betweenavenue asc limit 1", null);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			avenueCode = c.getString(1);
			txtProduct.setText(c.getString(30).toString().replace("\"", ""));
			txtProductCode
					.setText(c.getString(29).toString().replace("\"", ""));
			txtVersionCode
					.setText(c.getString(18).toString().replace("\"", ""));
			txtVersion.setText(c.getString(19).toString().replace("\"", ""));
			txtCarrier.setText(c.getString(7).toString().replace("\"", ""));
			txtSize.setText(c.getString(5).toString().replace("\"", ""));
			txtTotalAvisos
					.setText(c.getString(12).toString().replace("\"", ""));
			txtAvisos.setText(c.getString(11).toString().replace("\"", ""));
			realCost = c.getString(9).toString().replace("\"", "");
			imageName = c.getString(33).toString().replace("\"", "");
			id = c.getString(0).toString().replace("\"", "");
			String startingPoint = null;
			startingPoint = c.getString(28).replace("\"", "");
			String[] rowData = null;
			if (startingPoint.contains(" ")) {
				rowData = startingPoint.split(" ");
				txtCodigo.setText(rowData[0]);
			} else
				txtCodigo.setText(startingPoint);

			String[] rowData1 = null;
			rowData1 = c.getString(10).toString().split("/");
			txtlatFromRf.setText(rowData1[0]);
			txtLongFromRF.setText(rowData1[1]);
			c.moveToNext();
		}
		c.close();
		File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/" + imageName
				+ ".jpg");
		if (imgFile.exists()) {
			// Toast.makeText(getApplicationContext(),
			// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
			// 30000).show();
			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
					.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		} else {
			File noImg = new File(
					"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
			Bitmap myBitmap = BitmapFactory.decodeFile(noImg.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		}
	}

	public void ultino(String paramInt) {
		Set<String> set = db.getStartingPointList(paramInt);
		List<String> nonu = new ArrayList<String>(set);
		Collections.sort(nonu);
		String str1 = ((String) nonu.get(-1 + nonu.size())).toString();
		Cursor c = this.dbBill.rawQuery(
				"select * from tblbillboard where avenue= " + this.avenueCode
						+ " and Betweenavenue like '%" + str1 + "%' limit 1",
				null);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			avenueCode = c.getString(1);
			txtProduct.setText(c.getString(30).toString().replace("\"", ""));
			txtProductCode
					.setText(c.getString(29).toString().replace("\"", ""));
			txtVersionCode
					.setText(c.getString(18).toString().replace("\"", ""));
			txtVersion.setText(c.getString(19).toString().replace("\"", ""));
			txtCarrier.setText(c.getString(7).toString().replace("\"", ""));
			txtSize.setText(c.getString(5).toString().replace("\"", ""));
			txtTotalAvisos
					.setText(c.getString(12).toString().replace("\"", ""));
			txtAvisos.setText(c.getString(11).toString().replace("\"", ""));
			realCost = c.getString(9).toString().replace("\"", "");
			imageName = c.getString(33).toString().replace("\"", "");
			id = c.getString(0).toString().replace("\"", "");
			String startingPoint = null;
			startingPoint = c.getString(28).replace("\"", "");
			String[] rowData = null;
			rowData = startingPoint.split(" ");
			txtCodigo.setText(rowData[0]);
			String[] rowData1 = null;
			rowData1 = c.getString(10).toString().split("/");
			txtlatFromRf.setText(rowData1[0]);
			txtLongFromRF.setText(rowData1[1]);
			c.moveToNext();
		}
		c.close();
		Cursor cur = dbBill.rawQuery(
				"SELECT count(Avenue) as count FROM tblBillboard WHERE Avenue = "
						+ avenueCode, null);
		cur.moveToFirst();
		int icount = cur.getInt(0);
		txtTotalAvisos.setText(String.valueOf(icount));
		cur.close();
		File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/" + imageName
				+ ".jpg");
		if (imgFile.exists()) {
			// Toast.makeText(getApplicationContext(),
			// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
			// 30000).show();
			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
					.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		} else {
			File noImg = new File(
					"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
			Bitmap myBitmap = BitmapFactory.decodeFile(noImg.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		}
	}

	public void DeleteRecord(String startingPointforDelete, String ave)

	{
		Set<String> set = db.getStartingPointList(ave);
		List<String> nonu = new ArrayList<String>(set);
		Collections.sort(nonu);
		String str = String.valueOf(nonu.size());
		// Toast.makeText(getApplicationContext(), str, 2000).show();
		int j = 0;
		for (int i = 0; i < nonu.size(); i++) {
			String newPoint = nonu.get(i);

			if (newPoint.equals(startingPointforDelete)) {
				// Toast.makeText(getApplicationContext(),oldPoint,
				// 2000).show();
				j = i + 1;
				break;
			}

		}
		// Toast.makeText(getApplicationContext(),nonu.get(j), 20000).show();
		String selectQuery = "Select * from tblBillboard where  Avenue = "
				+ ave + " and Betweenavenue  like '%" + nonu.get(j)
				+ "%' limit 1";
		Cursor c = dbBill.rawQuery(selectQuery, null);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			avenueCode = c.getString(1);
			txtProduct.setText(c.getString(30).toString().replace("\"", ""));
			txtProductCode
					.setText(c.getString(29).toString().replace("\"", ""));
			txtVersionCode
					.setText(c.getString(18).toString().replace("\"", ""));
			txtVersion.setText(c.getString(19).toString().replace("\"", ""));
			txtCarrier.setText(c.getString(7).toString().replace("\"", ""));
			txtSize.setText(c.getString(5).toString().replace("\"", ""));
			txtTotalAvisos
					.setText(c.getString(12).toString().replace("\"", ""));
			txtAvisos.setText(c.getString(11).toString().replace("\"", ""));
			realCost = c.getString(9).toString().replace("\"", "");
			imageName = c.getString(33).toString().replace("\"", "");
			id = c.getString(0).toString().replace("\"", "");
			String startingPoint = null;
			startingPoint = c.getString(28).replace("\"", "");
			String[] rowData = null;
			rowData = startingPoint.split(" ");
			txtCodigo.setText(rowData[0]);
			// String[] rowData1 = null;
			// rowData1 = c.getString(10).toString().split("/");
			// txtlatFromRf.setText(rowData1[0]);
			// txtLongFromRF.setText(rowData[1]);
			c.moveToNext();
		}
		c.close();
		Cursor cur = dbBill.rawQuery(
				"SELECT count(Avenue) as count FROM tblBillboard WHERE Avenue = "
						+ avenueCode, null);
		cur.moveToFirst();
		int icount = cur.getInt(0);
		txtTotalAvisos.setText(String.valueOf(icount));
		cur.close();
		File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/" + imageName
				+ ".jpg");
		if (imgFile.exists()) {
			// Toast.makeText(getApplicationContext(),
			// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
			// 30000).show();
			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
					.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		} else {
			File noImg = new File(
					"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
			Bitmap myBitmap = BitmapFactory.decodeFile(noImg.getAbsolutePath());

			imageView.setImageBitmap(myBitmap);
		}

	}

	public void saveDataInhistoryTable() {
		this.dbBill
				.execSQL("CREATE TABLE IF NOT EXISTS tblBillboardhistory(ID INTEGER PRIMARY KEY ,OriginalID INTEGER, Avenue INTEGER,Date NNVARCHAR,Starttime NVARCHAR,Endtime NVARCHAR,Size NVARCHAR,Carrier NVARCHAR,CarrierDescription NVARCHAR,Quality NVARCHAR,RealCost NVARCHAR,LatandLong NVARCHAR,Numberofads NVARCHAR,Totaladsinthatlocation NVARCHAR,typeofads NVARCHAR,Visibilitycode NVARCHAR,Visibilitydescription NVARCHAR,Verificationdate NVARCHAR,Verificationdescription NVARCHAR,Versiocode NVARCHAR,Versiondescription NVARCHAR,Productcode NVARCHAR,Constant NVARCHAR,CategoryCode NVARCHAR,Categorydescription NVARCHAR,Subsectorcode NVARCHAR,Subsectordescription NVARCHAR,Sectorcode NVARCHAR,Sectordescription NVARCHAR,Betweenavenue NVARCHAR,Brandcode NVARCHAR,Branddescription NVARCHAR,Announcercode NVARCHAR,Announcerdescription NVARCHAR,Imagecode NVARCHAR,Agencycode NVARCHAR,Agencyname NVARCHAR,Condition NVARCHAR,Obstruction NVARCHAR); ");
		Cursor localCursor = this.dbBill.rawQuery(
				"select * from tblbillboard where avenue= " + this.avenueCode
						+ " and Betweenavenue like '%"
						+ this.txtCodigo.getText().toString() + "%' limit 1",
				null);
		localCursor.moveToFirst();
		if (localCursor.moveToFirst())
			do
				this.dbBill
						.execSQL("INSERT INTO tblBillboardhistory (OriginalID,Avenue,Date,Starttime,Endtime,Size,Carrier,CarrierDescription,Quality,RealCost,LatandLong,Numberofads,Totaladsinthatlocation,typeofads,Visibilitycode,Visibilitydescription,Verificationdate,Verificationdescription,Versiocode,Versiondescription,Productcode,Constant,CategoryCode,Categorydescription,Subsectorcode,Subsectordescription,Sectorcode,Sectordescription,Betweenavenue,Brandcode,Branddescription,Announcercode,Announcerdescription,Imagecode,Agencycode,Agencyname,Condition,Obstruction) VALUES ("
								+ localCursor.getString(0)
								+ ",'"
								+ localCursor.getString(1)
								+ "','"
								+ localCursor.getString(2)
								+ "','"
								+ localCursor.getString(3)
								+ "','"
								+ localCursor.getString(4)
								+ "','"
								+ localCursor.getString(5)
								+ "','"
								+ localCursor.getString(6)
								+ "','"
								+ localCursor.getString(7)
								+ "','"
								+ localCursor.getString(8)
								+ "','"
								+ localCursor.getString(9)
								+ "','"
								+ localCursor.getString(10)
								+ "','"
								+ localCursor.getString(11)
								+ "','"
								+ localCursor.getString(12)
								+ "','"
								+ localCursor.getString(13)
								+ "','"
								+ localCursor.getString(14)
								+ "','"
								+ localCursor.getString(15)
								+ "','"
								+ localCursor.getString(16)
								+ "','"
								+ localCursor.getString(17)
								+ "','"
								+ localCursor.getString(18)
								+ "','"
								+ localCursor.getString(19)
								+ "','"
								+ localCursor.getString(20)
								+ "','"
								+ localCursor.getString(21)
								+ "','"
								+ localCursor.getString(22)
								+ "','"
								+ localCursor.getString(23)
								+ "','"
								+ localCursor.getString(24)
								+ "','"
								+ localCursor.getString(25)
								+ "','"
								+ localCursor.getString(26)
								+ "','"
								+ localCursor.getString(27)
								+ "','"
								+ localCursor.getString(28)
								+ "','"
								+ localCursor.getString(29)
								+ "','"
								+ localCursor.getString(30)
								+ "','"
								+ localCursor.getString(31)
								+ "','"
								+ localCursor.getString(32)
								+ "','"
								+ localCursor.getString(33)
								+ "','"
								+ localCursor.getString(34)
								+ "','"
								+ localCursor.getString(35)
								+ "','"
								+ localCursor.getString(36)
								+ "','"
								+ localCursor.getString(37) + "');");
			while (localCursor.moveToNext());
		localCursor.close();
		Toast.makeText(getApplicationContext(), "Done", 2000).show();
	}

	public void cancelar() {

		Cursor c = this.dbBill.rawQuery(
				"select * from tblBillboardhistory where OriginalID= "
						+ this.id + " limit 1", null);
		if (c.getCount() != 1) {
			c.moveToFirst();
			while (!c.isAfterLast()) {
				avenueCode = c.getString(1);
				txtProduct
						.setText(c.getString(30).toString().replace("\"", ""));
				txtProductCode.setText(c.getString(29).toString()
						.replace("\"", ""));
				txtVersionCode.setText(c.getString(18).toString()
						.replace("\"", ""));
				txtVersion
						.setText(c.getString(19).toString().replace("\"", ""));
				txtCarrier.setText(c.getString(7).toString().replace("\"", ""));
				txtSize.setText(c.getString(5).toString().replace("\"", ""));
				txtTotalAvisos.setText(c.getString(12).toString()
						.replace("\"", ""));
				txtAvisos.setText(c.getString(11).toString().replace("\"", ""));
				realCost = c.getString(9).toString().replace("\"", "");
				imageName = c.getString(33).toString().replace("\"", "");
				id = c.getString(0).toString().replace("\"", "");
				String startingPoint = null;
				startingPoint = c.getString(28).replace("\"", "");
				String[] rowData = null;
				rowData = startingPoint.split(" ");
				txtCodigo.setText(rowData[0]);
				String[] rowData1 = null;
				rowData1 = c.getString(10).toString().split("/");
				txtlatFromRf.setText(rowData1[0]);
				txtLongFromRF.setText(rowData1[1]);
				c.moveToNext();
			}
			c.close();
			Cursor cur = dbBill.rawQuery(
					"SELECT count(Avenue) as count FROM tblBillboard WHERE Avenue = "
							+ avenueCode, null);
			cur.moveToFirst();
			int icount = cur.getInt(0);
			txtTotalAvisos.setText(String.valueOf(icount));
			cur.close();
			File imgFile = new File("/mnt/sdcard/Images/Outdoor/image/"
					+ imageName + ".jpg");
			if (imgFile.exists()) {
				// Toast.makeText(getApplicationContext(),
				// "/mnt/sdcard/Images/Outdoor/image/" + imageName + ".jpg",
				// 30000).show();
				Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
						.getAbsolutePath());

				imageView.setImageBitmap(myBitmap);
			} else {
				File noImg = new File(
						"/mnt/sdcard/Images/Outdoor/image/noimage.jpg");
				Bitmap myBitmap = BitmapFactory.decodeFile(noImg
						.getAbsolutePath());

				imageView.setImageBitmap(myBitmap);
			}

		} else {
			Toast.makeText(getApplicationContext(), "No Record Found", 20000)
					.show();

		}

	}

	protected void forNewStartingPoint(String paramString) {
		String str = paramString;
		int param = Integer.parseInt(paramString.substring(
				paramString.length() - 4, paramString.length()));
		paramString = paramString.substring(0, 4);
		param = param + 1;
		String num = "";
		if (String.valueOf(param).length() < 4) {

			num = "0" + String.valueOf(param);

		}
		paramString = paramString + num;
		Cursor c = dbBill.rawQuery(
				"select * from tblBillboard where Betweenavenue like '%"
						+ paramString + "%'", null);
		if (c.getCount() != 0) {
			txtCodigo.setText(str + "-A");

		} else {
			txtCodigo.setText(paramString);

		}

	}

	protected void contain(String str) {
		String point = "";
		String[] strat = null;
		strat = str.split("-");
		containStartingPoint cc = containStartingPoint.valueOf(strat[1]);
		switch (cc) {
		case A:
			point = strat[0] + "-B";
			break;
		case B:
			point = strat[0] + "-C";
			break;
		case C:
			point = strat[0] + "-D";
			break;
		case D:
			point = strat[0] + "-E";
			break;
		case E:
			point = strat[0] + "-F";
			break;
		case F:
			point = strat[0] + "-G";
			break;
		case G:
			point = strat[0] + "-H";
			break;
		case H:
			point = strat[0] + "-I";
			break;
		case I:
			point = strat[0] + "-J";
			break;
		case J:
			point = strat[0] + "-K";
			break;
		case K:
			point = strat[0] + "-L";
			break;
		case L:
			point = strat[0] + "-M";
			break;
		case M:
			point = strat[0] + "-N";
			break;
		case N:
			point = strat[0] + "-O";
			break;
		case O:
			point = strat[0] + "-P";
			break;
		case P:
			point = strat[0] + "-Q";
			break;
		case Q:
			point = strat[0] + "-R";
			break;
		case R:
			point = strat[0] + "-S";
			break;
		case S:
			point = strat[0] + "-T";
			break;
		case T:
			point = strat[0] + "-U";
			break;
		case U:
			point = strat[0] + "-V";
			break;
		case V:
			point = strat[0] + "-W";
			break;
		case W:
			point = strat[0] + "-X";
			break;
		case X:
			point = strat[0] + "-Y";
			break;
		case Y:
			point = strat[0] + "-Z";
			break;
		case Z:
			point = strat[0] + "-A";
			break;
		}
		Cursor c = dbBill.rawQuery(
				"select * from tblBillboard where Betweenavenue like '%"
						+ point + "%'", null);
		if (c.getCount() != 0) {
			contain(point);

		} else {
			txtCodigo.setText(point);

		}

	}
}
